from django.shortcuts import render, redirect
from apps.user.models import User
from django.core.urlresolvers import reverse


import re
# Create your views here.


# /user/register
def register(request):
    """显示注册页面"""
    return render(request,'register.html')


def register_handle(request):
    """用户注册处理"""
    # 1.接受浏览器传过来的数据
    username = request.POST.get('user_name')  # 获取用户名
    passwd = request.POST.get('pwd') #获取用户密码
    emial = request.POST.get("email") # 获取用户邮箱
    allow = request.POST.get('allow')  # 获取用户是否同意协议
    cpwd = request.POST.get('cpwd')  # 获取第二次密码


    # 2.进行数据校验
    if not all([username,passwd,emial]):
        # 说明数据不完整
        return render(request,'register.html',{'errmsg':"数据不完整"})
    # 校验邮箱
    if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',emial):
        return render(request,'register.html',{'errmsg':"邮箱不合法"})
    # 是否同意协议
    if allow != 'on':
        return render(request,'register.html',{'errmsg':"请同意用户协议"})
    # 判断两次密码是否相同
    if cpwd != passwd:
        return render(request,'register.html',{'errmsg':"两次密码不相同"})



    # 3.进行业务处理：进行用户注册
    User.objects.create_user(username,emial,passwd)
    User.is_active = 0 # 用户为非激活状态 首次注册的时候
    # 4.返回应答  跳转到首先
    #
    return  redirect(reverse('goods:index'))

